let outerTable;

layui.config({
    version: '1606406696877' //为了更新 js 缓存，可忽略
});

layui.use(['layer', 'upload', 'table', 'laydate', 'element', 'form'], function () {
    let layer = layui.layer //弹层
        , table = layui.table //表格
        , laydate = layui.laydate //日期选择
        , form = layui.form
        , upload = layui.upload

    // 赋值给外部引用table
    outerTable = layui.table;

    //执行一个 table 实例
    table.render({
        elem: '#bookList'
        , url: '/book/all' //数据接口
        , request: {
            pageName: 'page' //页码的参数名称，默认：page
            , limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        , title: '图书表'
        , page: {
            limit: 4,
            limits: [2, 4, 6]
        } //开启分页
        , cols: [
            [ //表头
                // {type: 'radio', title: '选择', rowspan: 2, align: 'center'},
                {type: 'numbers', title: '序号', minWidth: 40, width: 60, rowspan: 2, align: 'center'}
                , {field: 'title', title: '题名', minWidth: 170, width: 170, rowspan: 2, align: 'center'}
                , {
                title: '封面', minWidth: 130, width: 130, rowspan: 2, align: 'center', templet: function (d) {
                    console.log("img值是：" + d.img);
                    // if (d.img !== undefined || d.img !== null || d.img !== "" || !d.img) {
                    if (d.img) {
                        return "<img src='/path/img/" + d.img.split("/")[4] + "' width='100' height='100'>";
                    } else {
                        return "<img src='/img/default_book.png' width='100' height='100'>";
                    }
                }
            }
                , {
                title: '作者', minWidth: 100, width: 120, rowspan: 2, align: 'center',
                templet: function (d) {
                    if (d.author !== undefined) {
                        return d.author;
                    } else {
                        return "——"
                    }
                }
            }
                , {
                title: '出版社', minWidth: 120, width: 140, rowspan: 2, align: 'center',
                templet: function (d) {
                    if (d.press !== undefined) {
                        return d.press;
                    } else {
                        return "——";
                    }
                }
            }
                , {
                title: '出版时间', minWidth: 80, width: 100, rowspan: 2, align: 'center',
                templet: function (d) {
                    if (d.pressTime !== undefined) {
                        return d.pressTime;
                    } else {

                        return "——";
                    }
                }
            }
                , {align: 'center', title: '中图分类法', colspan: 2}
                , {
                title: '主题', minWidth: 90, width: 100, rowspan: 2, align: 'center',
                templet: function (d) {
                    if (d.keyword !== undefined) {
                        return d.keyword;
                    } else {

                        return "设置主题类别后才能上架！";
                    }
                }

            }
                , {
                title: '状态', minWidth: 80, width: 100, rowspan: 2, align: 'center',
                templet: function (d) {
                    // 1表示已推荐，0表示未推荐
                    if (d.status === 0) {
                        return "<input id='" + d.id + "' type='checkbox' lay-skin='switch' lay-text='推荐|不推荐' lay-filter='filter'>";
                    } else {
                        return "<input id='" + d.id + "' type='checkbox' lay-skin='switch' lay-text='推荐|不推荐' lay-filter='filter' checked>";
                    }
                }
            }

                , {align: 'center', title: '操作', toolbar: '#bookListBar', rowspan: 2, width: 140}
            ]
            ,
            [
                {
                    field: '', title: '标记符号', width: 115, align: 'center', templet: function (d) {
                        if (d.category !== undefined) {
                            return d.category.split(" ")[0];
                        } else {
                            return "请完善!";
                        }
                    }
                },
                {
                    field: '', title: '类目名称', width: 115, align: 'center', templet: function (d) {
                        if (d.category !== undefined) {
                            return d.category.split(" ")[1];
                        } else {
                            return "请完善!";
                        }
                    }
                },
            ]
        ]
        ,
        parseData: function (res) {
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": res.data //解析数据列表
            };
        }
        ,done: function (res, curr, count) {
            console.log(res);
            console.log(curr);
            console.log(count);
            res.data.forEach(function (item, index) {
                if (item.keyword === undefined) {
                    let tr = $(".layui-table").find("tbody tr[data-index='" + index + "']");
                    // tr.css("background-color", "#f38181");
                    // 给1-0-9列添加样式
                    tr.find(".laytable-cell-1-0-7").css("color","#fc5185");
                    tr.find(".laytable-cell-1-1-0").css("color","#fc5185");
                    tr.find(".laytable-cell-1-1-1").css("color","#fc5185");
                }
            });
        }
    });


    //监听工具条
    table.on('tool(bookTable)', function (obj) { //注：tool 是工具条事件名，bookTable 是 table 原始容器的属性 lay-filter="对应的值"
        let book = obj.data; //获得当前行数据
        let layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        let tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

        if (layEvent === 'edit') { // 修改
            location.href = "/book/edit?id=" + book.id;
        } else if (layEvent === 'delete') { //删除
            layer.confirm('确认删除<span style="color: red">《' + book.title + '》</span>么？', function (index) {
                layer.close(index);
                //向服务端发送删除指令
                $.ajax({
                    url: '/api/deleBook',
                    type: 'post',
                    dataType: 'json',
                    data: JSON.stringify(book),
                    contentType: 'application/json;charset=UTF-8',
                    success: function (res) {
                        if (res.code === 0) {
                            // setTimeout(function () {
                            //     window.open("/admin/bookList", "main");
                            // }, 800);
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                            layer.msg('删除成功', {icon: 1, time: 1400});
                        } else {
                            layer.msg("删除出错，请稍后重试……", {icon: 5, anim: 6});
                        }
                    },
                    error: function () {
                        layer.msg("出现未知错误……", {icon: 5, anim: 6});
                    }
                })
            });
        }
    });


    // 监听推荐状态（开关）
    form.on('switch(filter)', function (data) {
            let obj = {bookId: data.elem.id, adminId: admin.id};
            // true为推荐，反之不推荐
            if (data.elem.checked) {
                let target = "/admin/recommend/on";
                $.ajax({
                    // headers必须添加，否则会报415错误
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    },
                    type: 'POST',
                    dataType: "json", //表示返回值类型，不必须
                    data: JSON.stringify(obj),
                    url: target,
                    success: function (result) {
                        // 推荐返回的是Boolean字符串
                        if (result) {
                            layer.msg('已推荐！', {icon: 1, time: 900});
                        } else {
                            layer.msg('操作失败。。', {icon: 0, time: 900});
                        }
                    },
                    error: function () {
                        layer.msg('系统异常。。', {icon: 3, time: 900});
                    }
                });
            } else {
                let target = "/admin/recommend/off";
                $.ajax({
                    // headers必须添加，否则会报415错误
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    },
                    type: 'POST',
                    dataType: "json", //表示返回值类型，不必须
                    data: JSON.stringify(obj),
                    url: target,
                    success: function (result) {
                        // 不推荐返回的是受影响的行数（字符串）
                        if (result !== 0) {
                            layer.msg('不开心。。', {icon: 5, time: 900});
                        } else {
                            layer.msg('操作失败。。', {icon: 0, time: 900});
                        }
                    },
                    error: function () {
                        layer.msg('系统异常。。', {icon: 3, time: 900});
                    }
                });
            }
        }

        // 以下是get方式
        // if (data.elem.checked) {
        //     let url = "/admin/" + admin.id + "/recommend/on/" + data.elem.id;
        //     $.get(url, function (result) {
        //         // 消息层默认3s
        //         layer.msg('已推荐！', {icon: 1, time: 900});
        //         console.log(result);
        //     });
        // } else {
        //     let url = "/admin/" + admin.id + "/recommend/off/" + data.elem.id;
        //     $.get(url, function (result) {
        //         layer.msg('不开心。。', {icon: 5, time: 900});
        //         console.log(result);
        //     });
        // }
    );


    // function modifyStatus(target, data) {
    //     $.ajax({
    //         // headers必须添加，否则会报415错误
    //         headers: {
    //             'Accept': 'application/json',
    //             'Content-Type': 'application/json'
    //         },
    //         type: 'POST',
    //         dataType: "json", //表示返回值类型，不必须
    //         data: JSON.stringify(data),
    //         url: target,
    //         success: function (result) {
    //             console.log(result);
    //         }
    //     });
    // }


    // 条件查询分页
    $("#searchBtn").on("click", function () {

        let title = $("#title").val();
        let categoryId = $("#categoryId").val();
        let themeId = $("#themeId").val();
        let status = $("#status").val();
        console.log("title:" + title + "\ncategoryId:" + categoryId + "\nthemeId:" + themeId + "\nstatus:" + status);

        // 空值为真
        let flag1 = title == null || title === "";
        let flag2 = categoryId == null || categoryId === "";
        let flag3 = themeId == null || themeId === "";
        let flag4 = status == null || status === "";

        // 全部为真（没有条件输入）
        if (flag1 && flag2 && flag3 && flag4) {
            layer.msg('请选择查询条件！', {icon: 0});
            return;
        }

        let req = {};
        req.title = title;
        req.categoryId = categoryId;
        req.themeId = themeId
        req.status = status;

        // 表格重载
        table.reload('bookList', {
            url: "/book/all",
            method: "post",
            contentType: "application/json",
            where: req, // req是JSON数据
            request: {
                pageName: 'page' //页码的参数名称，默认：page
                , limitName: 'limit' //每页数据量的参数名，默认：limit
            }
            , page: {
                curr: 1,
                limit: 4,
                limits: [2, 4, 6, 8, 10]
            } //开启分页
        })
    });


    // 导入书单
    let uploadInst = upload.render({
        elem: '#uploadExcel' //绑定元素
        ,url: '/book/upload/excel' //上传接口
        ,exts: 'xls|xlsx'   // 允许的文件格式
        ,size: 4096 // 单位KB，最大允许4MB
        ,done: function(res){
            if (res.row !== 0) {
                layer.open({title: '提示', icon: 1, content: '书单导入成功，快去看看吧', shadeClose: true, time: 2000});
            } else {
                layer.open({title: '提示', icon: 0, content: '导入书单失败，请稍后再试！', shadeClose: true, time: 2000});
            }
        }
        ,error: function(){
            //请求异常回调
            layer.open({title: '提示', icon: 2, content: '网络异常！', shadeClose: true, time: 3000});
        }
    });


});


